
//生产消费者模型 MyBlockingQueue
class MyBlockingQueue{
    private String[] elems = null;

    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;
    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }

    public void put(String elem) throws InterruptedException {
        synchronized(this) {
            while (size >= elems.length) {
                //队列满 阻塞等待take的唤醒
                this.wait();
            }
            elems[tail++] = elem;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;
            //唤醒下面take中队列为空的情况
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized(this) {
            if (size == 0) {
                this.wait();
            }
            String value = elems[head++];
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            //唤醒上面队列满的情况
            this.notify();
            return value;
        }
    }
}
public class Demo31 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(100);
        //t1 生产者
        Thread t1 = new Thread(() -> {
           try{
               int count = 1;
               while(true){
                   queue.put(count+"");
                   System.out.println("生产："+count++);
               }
           }catch(InterruptedException e){
               e.printStackTrace();
           }
        });
        //消费者
        Thread t2 = new Thread(() -> {
           try{
               while(true){
                   String value = queue.take();
                   System.out.println("消费"+value);
                   Thread.sleep(1000);
               }
           }catch(InterruptedException e){
               e.printStackTrace();
           }
        });
        t1.start();
        t2.start();

    }
}
